package com.baosight.risk.web.jlta;

import com.baosight.risk.api.fltd.FltdTaskService;
import com.baosight.risk.api.jlta.JltaRebackService;
import com.baosight.risk.api.jlta.JltaTaskService;
import com.baosight.risk.api.jlta.JltaTeamService;
import com.baosight.risk.api.xtdc.XtdcAttachService;
import com.baosight.risk.base.controller.BaseController;
import com.baosight.risk.base.redis.RedisLock;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.file.FileManager;
import com.baosight.risk.common.result.AjaxResult;
import com.baosight.risk.common.utils.DateUtils;
import com.baosight.risk.common.utils.ExcelUtil;
import com.baosight.risk.mapper.jlta.JltaTaskMapper;
import com.baosight.risk.service.fltd.entity.FltdTask;
import com.baosight.risk.service.jlta.entity.JltaReback;
import com.baosight.risk.service.jlta.entity.JltaTask;
import com.baosight.risk.service.jlta.entity.JltaTeamUser;
import com.baosight.risk.service.jlta.vo.JltaTaskVO;
import com.baosight.risk.service.jlta.vo.JltaTeamUserVO;
import com.baosight.risk.service.jlta.vo.MutiTeamVO;
import com.baosight.risk.service.xtdc.entity.XtdcAttach;
import com.baosight.risk.service.xtzy.entity.XtzyUser;
import com.baosight.risk.web.netty.SocketIO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.MediaType;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.logging.SimpleFormatter;
import java.util.stream.Collectors;

/**
 * 作者： lishaoqing
 * 时间： 2019年07月08日
 * 描述： JltaTaskController
 * 版本: v1.0
 */
@Api(value = "任务管理", description = "任务管理", produces = MediaType.APPLICATION_JSON)
@Slf4j
@RestController
@RequestMapping("/jlta/task")
public class JltaTaskController extends BaseController {

    @Autowired
    private JltaTaskService jltaTaskService;
    @Autowired
    private XtdcAttachService xtdcAttachService;
    @Autowired
    private FileManager fileManager;
    @Autowired
    private JltaTeamService jltaTeamService;
    @Autowired
    private FltdTaskService fltdTaskService;
    @Autowired
    private JltaTaskMapper taskMapper;
    @Autowired
    private RedisLock redisLock;
    @Autowired
    private JltaRebackService rebackService;
    @Autowired
    private SocketIO socketServer;

    @ApiOperation("获取任务信息列表")
    @GetMapping("taskList")
    public AjaxResult taskList(JltaTask jltaTask) {
        return getResultPage(jltaTaskService.selectTaskList(jltaTask));
    }

    @ApiOperation("获取任务反饋列表")
    @GetMapping("rebackList")
    public AjaxResult rebackList(JltaReback reback) {
        startPage();
        return getResultPage(rebackService.select(reback));
    }

    @ApiOperation("根据ids获取任务列表")
    @GetMapping("getTasksByIds")
    public AjaxResult getTasksByIds(@RequestParam("id") String id) {

        return success(jltaTaskService.getTasksByIds(id));
    }

    @ApiOperation("新增任务")
    @PostMapping("addTask")
    public AjaxResult addTask(@RequestBody JltaTaskVO vo) {
        XtzyUser sysUser = getUser();
        String userCode = sysUser.getUserCode();
        String taskId = UUID.randomUUID().toString();
        Date now = new Date();
        String priority = vo.getPriority();
        JltaTask jltaTask = new JltaTask();
        jltaTask.setId(taskId);
        jltaTask.setTaskName(vo.getTaskName());
        jltaTask.setPriority(vo.getPriority());
        if ("1".equals(priority)) {
            jltaTask.setPriorityName("高");
        } else if ("2".equals(priority)) {
            jltaTask.setPriorityName("中");
        } else {
            jltaTask.setPriorityName("低");
        }
        jltaTask.setTeamId(vo.getTeamId());
        jltaTask.setTeamName(vo.getTeamName());
        jltaTask.setCreateBy(userCode);
        jltaTask.setCreateTime(now);
        jltaTask.setExt5(sysUser.getUserDesc());
        jltaTask.setRemark(vo.getRemark());
        jltaTask.setStatus("0");
        jltaTask.setStatusName("草稿");
        jltaTask.setPlanDate(vo.getPlanDate());
        Integer result = jltaTaskService.addTask(jltaTask);
        if (result == 0) {
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    @ApiOperation("获取任务中的附件")
    @GetMapping("fileList")
    public AjaxResult fileList(@RequestParam("id") String id) {
        return AjaxResult.success("操作成功", jltaTaskService.selectFileList(id));
    }

    @ApiOperation("获取任务反馈中的附件")
    @GetMapping("rebackFileList")
    public AjaxResult rebackFileList(@RequestParam("id") String id) {
        return AjaxResult.success("操作成功", rebackService.selectFileList(id));
    }

    @ApiOperation("新增任务带附件")
    @PostMapping("uploadTask")
    public AjaxResult uploadResource(HttpServletRequest request) throws Exception {
        XtzyUser sysUser = getUser();
        String userCode = sysUser.getUserCode();

        //转换request
        ShiroHttpServletRequest shiroRequest = (ShiroHttpServletRequest) request;
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        MultipartHttpServletRequest multipartRequest = commonsMultipartResolver.resolveMultipart((HttpServletRequest) shiroRequest.getRequest());
        //获取页面传参
        String businessCode = multipartRequest.getParameter("businessCode");
        String teamId = multipartRequest.getParameter("teamId");
        String teamName = multipartRequest.getParameter("teamName");
        String taskCode = multipartRequest.getParameter("taskCode");
        String taskName = multipartRequest.getParameter("taskName");
        String priority = multipartRequest.getParameter("priority");
        String remark = multipartRequest.getParameter("remark");
        String planDateStr = multipartRequest.getParameter("planDate");//计划完成时间
        //毫秒值转时间
        Long aLong = Long.valueOf(planDateStr);
        Date planDate = new Date();
        planDate.setTime(aLong);
        String taskId = UUID.randomUUID().toString();
        Date now = new Date();

        //获取附件
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (String key : fileMap.keySet()) {
            MultipartFile multipartFile = fileMap.get(key);
            InputStream inputStream = multipartFile.getInputStream();
            String filename = multipartFile.getOriginalFilename();
            long fileSize = multipartFile.getSize();

            FileManager.Config config = fileManager.getConfig();
            config.setInputStream(inputStream);
            config.setBusinessCode(businessCode);
            config.setFilename(filename);

            //生成目录
            String dir = fileManager.generateDir(config);
            String filepath = dir + "/" + filename;
            //保存文件
            multipartFile.transferTo(new File(filepath));

            String fileType = "file";
            int indx = filename.lastIndexOf(".");
            if (indx > 0 && indx < filename.length() - 1) {
                fileType = filename.substring(indx + 1).toLowerCase();
            }
            //存入数据库
            XtdcAttach attach = (XtdcAttach) BeanUtils.initBean(new XtdcAttach());
            attach.setFileName(filename);
            attach.setFilePath(filepath);
            attach.setFileSize(fileSize);
            attach.setFileType(fileType);
            attach.setFolderId("1");
            attach.setSourceGuid(taskId);
            attach.setSourceModel("T_JLTA_TASK");
            xtdcAttachService.insert(attach);
        }
        JltaTask jltaTask = new JltaTask();
        jltaTask.setId(taskId);
        jltaTask.setTaskCode(taskCode);
        jltaTask.setTaskName(taskName);
        jltaTask.setPriority(priority);
        jltaTask.setTeamId(teamId);
        jltaTask.setExt5(sysUser.getUserDesc());
        jltaTask.setTeamName(teamName);
        jltaTask.setRemark(remark);
        jltaTask.setPlanDate(planDate);
//            jltaTask.setFileId(attach.getId());
        jltaTask.setCreateBy(userCode);
        jltaTask.setCreateTime(now);
        jltaTask.setStatus("0");
        jltaTask.setStatusName("草稿");
        jltaTaskService.addTask(jltaTask);
        return AjaxResult.success();
    }

    @ApiOperation("删除任务")
    @PutMapping("deleteTask")
    public AjaxResult deleteTask(@RequestBody MutiTeamVO teamVO) {
        XtzyUser sysUser = getUser();
        String userCode = sysUser.getUserCode();
        String teamId = teamVO.getTeamId();
        List<String> ids = teamVO.getIds();
        /**
         * 获得团队角色
         */
        String role = getRole(sysUser, teamId);
        if ("0".equals(role)) {
            return error("只有团队创建人和项目负责人可以删除任务！");
        }
        for (String id : ids) {
            JltaTask jltaTask = new JltaTask();
            jltaTask.setId(id);
            jltaTask.setStatus("8");
            jltaTask.setUpdateBy(userCode);
            jltaTask.setUpdateTime(new Date());
            jltaTaskService.deleteTask(jltaTask);
            rebackService.deleteByTaskGuid(id);
        }
        return AjaxResult.success();
    }

    @ApiOperation("修改任务")
    @PostMapping("editTask")
    public AjaxResult editTask(@RequestBody MutiTeamVO mutiTeamVO) {
        XtzyUser sysUser = getUser();
        String userCode = sysUser.getUserCode();
        JltaTaskVO vo = mutiTeamVO.getJltaTaskVO();
        String teamId = mutiTeamVO.getTeamId();
        String role = getRole(sysUser, teamId);
        if ("0".equals(role)) {
            return error("只有团队创建人和项目负责人能够修改!");
        }
        if (vo != null) {
            String priority = vo.getPriority();
            JltaTask jltaTask = new JltaTask();
            jltaTask.setId(vo.getId());
            jltaTask.setTaskCode(vo.getTaskCode());
            jltaTask.setTaskName(vo.getTaskName());
            jltaTask.setPriority(vo.getPriority());
            jltaTask.setPlanDate(vo.getPlanDate());
            if ("1".equals(priority)) {
                jltaTask.setPriorityName("高");
            } else if ("2".equals(priority)) {
                jltaTask.setPriorityName("中");
            } else {
                jltaTask.setPriorityName("低");
            }
            jltaTask.setRemark(vo.getRemark());
            jltaTask.setUpdateBy(userCode);
            jltaTask.setUpdateTime(new Date());
            Integer result = jltaTaskService.editTask(jltaTask);
            if (result > 0) {
                return AjaxResult.success();
            }
        }
        return AjaxResult.success();
    }

    @PostMapping("/exportJltaTask")
    @ApiOperation("导出任务列表")
    public AjaxResult exportExcel(@RequestBody(required = false) JltaTask jltaTask) {
        ExcelUtil<JltaTask> excel = new ExcelUtil<>(JltaTask.class);
        List<JltaTask> jltaTasks = jltaTaskService.selectTaskList(jltaTask);
        return excel.exportExcel(jltaTasks, "团队任务列表", null);
    }

    @ApiOperation("处理任务")
    @GetMapping("dealWithTask")
    public AjaxResult dealWithTask(@RequestParam("id") String id) {
        Date now = new Date();
        FltdTask fltdTask = fltdTaskService.selectTaskByTodoGuid(id);
        fltdTask.setStatus("close");
        fltdTask.setStatusName("完成");
        fltdTask.setFactEndDate(now);
        fltdTask.setAuditCode(getUser().getUserCode());
        fltdTask.setAuditName(getUser().getUserDesc());
        fltdTask.setUpdateTime(now);
        fltdTask.setUpdateBy(getUserName());
        if (fltdTaskService.updateTaskStatus(fltdTask) > 0) {
            JltaTask taskQ = new JltaTask();
            taskQ.setId(fltdTask.getBizGuid());
            taskQ.setStatus("2");
            taskQ.setStatusName("完结");
            jltaTaskService.update(taskQ);
            // 发送通知
            XtzyUser userMsg = new XtzyUser();
            userMsg.setUserCode(getUser().getUserCode());
            userMsg.setUserDesc(getUser().getUserDesc());
            userMsg.setExt1(getUser().getExt1());
            userMsg.setExt2(getUser().getExt2());
            userMsg.setExt3("close");
            socketServer.sendTaskMsgToAll(userMsg);
            return success();
        } else {
          return error();
        }
    }

    @PostMapping("assignTask")
    @ApiOperation("分配任务")
    public AjaxResult assignTask(@RequestBody MutiTeamVO mutiTeamVO) {
        XtzyUser sysUser = getUser();
        String teamId = mutiTeamVO.getTeamId();
        JltaTaskVO task = mutiTeamVO.getJltaTaskVO();
        List<JltaTeamUserVO> teamUserList = mutiTeamVO.getTeamUserVOList();
        String role = getRole(sysUser, teamId);
        if ("0".equals(role)) {
            return error("当前用户没有操作权限！");
        }
        if (CollectionUtils.isNotEmpty(teamUserList)) {
            StringBuffer assignNames = new StringBuffer();
            StringBuffer assignCodes = new StringBuffer();
            teamUserList.forEach(n -> {
                assignNames.append(n.getUserName());
                assignNames.append(",");
                assignCodes.append(n.getUserCode());
            });
            assignCodes.append(task.getId());
            //分布式锁
            redisLock.lock(assignCodes.toString(), 100L);
            JltaTask jltaTask = taskMapper.selectByPrimaryKey(task.getId());
            if (!"0".equals(jltaTask.getStatus())) {
                redisLock.unLock(assignCodes.toString());
                return error("已发送待办,请勿重复点击！");
            }
            String substring = assignNames.substring(0, assignNames.length() - 1);
            String acctYear = DateUtils.format(new Date(), "yyyy");
            String quarterCurrent = DateUtils.getQuarter(new Date());
            FltdTask taskVO = (FltdTask) BeanUtils.initBean(new FltdTask());
            taskVO.setFlowNo("renwuzhongxin");
            taskVO.setFlowName("任务中心");
            taskVO.setAcctYear(acctYear);
            taskVO.setQuarterCode(quarterCurrent);
            taskVO.setQuarterName(DateUtils.getQuarterName(taskVO.getQuarterCode()));
            taskVO.setFirstUserCode(sysUser.getUserCode());
            taskVO.setFirstUserName(sysUser.getUserDesc());
            taskVO.setBizGuid(task.getId());
            taskVO.setGroupFlag("N");
            String bizDesc = task.getTaskName() + "-" + taskVO.getAcctYear() + "年度";
            taskVO.setBizDesc(bizDesc);
            for (JltaTeamUserVO user : teamUserList) {
                taskVO.setBeforeUserCode(sysUser.getUserCode());
                taskVO.setBeforeUserName(sysUser.getUserDesc());
                taskVO.setCurrUserCode(user.getUserCode());
                taskVO.setCurrUserName(user.getUserName());
                taskVO.setCompCode(user.getCompCode());
                taskVO.setCompName(user.getCompName());
                taskVO.setPageUrl("/jlta/taskcopy/taskA01");
                taskVO = (FltdTask) BeanUtils.initBean(taskVO);
                taskVO.setTodoGuid(UUID.randomUUID().toString());
                taskVO.setTodoType("8");
                taskVO.setStatus("open");
                taskVO.setStatusName("进行中");
                taskVO.setRemark("提交");
                taskVO.setFactStartDate(new Date());
                fltdTaskService.insert(taskVO);
                // 发送通知
                XtzyUser userMsg = new XtzyUser();
                userMsg.setUserCode(user.getUserCode());
                userMsg.setUserDesc(user.getUserName());
                userMsg.setExt1(user.getCompCode());
                userMsg.setExt2(user.getCompName());
                userMsg.setExt3("open");
                socketServer.sendTaskMsgToAll(userMsg);
            }
            JltaTask taskQ = new JltaTask();
            taskQ.setId(task.getId());
            taskQ.setStatus("1");
            taskQ.setStatusName("待办");
            taskQ.setAssign(substring);
            jltaTaskService.update(taskQ);
            //释放锁
            redisLock.unLock(assignCodes.toString());
        }
        return success();
    }

    /**
     * 获得团队角色
     */
    private String getRole(XtzyUser sysUser, String teamId) {
        JltaTeamUser jltaTeamUserQ = new JltaTeamUser();
        jltaTeamUserQ.setUserCode(sysUser.getUserCode());
        jltaTeamUserQ.setTeamId(teamId);
        JltaTeamUser jltaTeamUser1 = jltaTeamService.selectOne(jltaTeamUserQ);
        String role = jltaTeamUser1.getRole();
        return role;
    }

    @PostMapping("assignTaskApproval")
    @ApiOperation("下发任务")
    @Transactional
    public AjaxResult assignTaskApproval(@RequestBody MutiTeamVO mutiTeamVO) {
        XtzyUser sysUser = getUser();
        String teamId = mutiTeamVO.getTeamId();
        JltaTaskVO task = mutiTeamVO.getJltaTaskVO();
        String role = getRole(sysUser, teamId);
        if ("0".equals(role)) {
            return error("当前用户没有操作权限！");
        }
        if ("".equals(task.getAssign())) {
            return error("没有分配任务给团队成员");
        }
        //1、根据任务主表拿到已经分配好的任务,状态：01:草稿,设置其审批状态
        JltaReback rebackQ = new JltaReback();
        rebackQ.setStatus("01");
        rebackQ.setTaskId(task.getId());
        List<JltaReback> rebacks = rebackService.select(rebackQ);
        if (CollectionUtils.isNotEmpty(rebacks)) {
            //分布式锁
            redisLock.lock(rebacks.toString(), 1000L);
            //将审批状态更新
            List<String> rebackIds = rebacks.stream().map(JltaReback::getId).collect(Collectors.toList());
            rebackService.updateIsapprovalByIds(rebackIds, mutiTeamVO.getIsapproval());
            String acctYear = DateUtils.format(new Date(), "yyyy");
            String quarterCurrent = DateUtils.getQuarter(new Date());
            //给分配人发送待办
            for (JltaReback reback : rebacks) {
                FltdTask taskVO = new FltdTask();
                taskVO.setFlowNo("renwuzhongxin");
                taskVO.setFlowName("任务中心");
                taskVO.setAcctYear(acctYear);
                taskVO.setQuarterCode(quarterCurrent);
                taskVO.setQuarterName(DateUtils.getQuarterName(taskVO.getQuarterCode()));
                taskVO.setFirstUserCode(sysUser.getUserCode());
                taskVO.setFirstUserName(sysUser.getUserDesc());
                taskVO.setBizGuid(reback.getId());
                taskVO.setGroupFlag("N");
                String bizDesc = task.getTaskName() + "-" + reback.getTeamName();
                taskVO.setBizDesc(bizDesc);
                taskVO.setBeforeUserCode(sysUser.getUserCode());
                taskVO.setBeforeUserName(sysUser.getUserDesc());
                taskVO.setCurrUserCode(reback.getUserCode());
                taskVO.setCurrUserName(reback.getUserDesc());
                taskVO.setPageUrl("/jlta/taskcopy/taskA01");
                taskVO = (FltdTask) BeanUtils.initBean(taskVO);
                taskVO.setTodoGuid(reback.getExt2());//todoGuid
                taskVO.setTodoType("8");
                taskVO.setStatus("open");
                taskVO.setStatusName("进行中");
                taskVO.setRemark("提交");
                taskVO.setFactStartDate(new Date());
                fltdTaskService.insert(taskVO);
                // 发送通知
                XtzyUser userMsg = new XtzyUser();
                userMsg.setUserCode(reback.getUserCode());
                userMsg.setUserDesc(reback.getUserDesc());
                userMsg.setExt1(reback.getTeamId());
                userMsg.setExt2(reback.getTeamName());
                userMsg.setExt3("open");
                socketServer.sendTaskMsgToAll(userMsg);
                redisLock.unLock(rebacks.toString());
            }
        } else {
            return error("没有可下发的成员，请重新分配成员！");
        }
        //将状态改为下发
        rebackService.updateRebackStatus(rebacks);
        JltaTask taskQ = new JltaTask();
        taskQ.setIsapproval(mutiTeamVO.getIsapproval());
        taskQ.setId(task.getId());
        taskQ.setStatus("1");
        taskQ.setStatusName("待办");
        jltaTaskService.update(taskQ);
        return success("下发成功");

    }

    @PostMapping("doSubmitTask")
    @ApiOperation("提交任务==产生待办")
    @Transactional
    public AjaxResult doSubmitTask(@RequestBody JltaReback reback) {
        Date now = new Date();
        //1,关闭上一条Fltdtask
        FltdTask fltdTask = fltdTaskService.selectTaskByTodoGuid(reback.getExt2());
        fltdTask.setStatus("close");
        fltdTask.setStatusName("完成");
        fltdTask.setAuditCode(getUser().getUserCode());
        fltdTask.setAuditName(getUser().getUserDesc());
        fltdTask.setFactEndDate(now);
        fltdTask.setUpdateBy(getUserName());
        fltdTask.setUpdateTime(now);
        fltdTaskService.updateTaskStatus(fltdTask);
        //2,更新反馈表属性,状态改为 03:已提交
        String TodoGuid = UUID.randomUUID().toString();
        reback.setExt2(TodoGuid);
        reback.setStatus("03");
        reback.setStatusName("已提交");
        rebackService.update(reback);
        //3,产生待办
        XtzyUser user = getUser();
        String acctYear = DateUtils.format(new Date(), "yyyy");
        String quarterCurrent = DateUtils.getQuarter(new Date());
        FltdTask taskVO = new FltdTask();
        taskVO.setFlowNo("renwuzhongxin");
        taskVO.setFlowName("任务中心");
        taskVO.setAcctYear(acctYear);
        taskVO.setQuarterCode(quarterCurrent);
        taskVO.setQuarterName(DateUtils.getQuarterName(taskVO.getQuarterCode()));
        taskVO.setFirstUserCode(user.getUserCode());//将任务提交给发起人
        taskVO.setFirstUserName(user.getUserDesc());//
        taskVO.setBizGuid(reback.getId());
        taskVO.setGroupFlag("N");
        String bizDesc = reback.getTaskName() + "-" + reback.getTeamName();
        taskVO.setBizDesc(bizDesc);
        taskVO.setBeforeUserCode(user.getUserCode());
        taskVO.setBeforeUserName(user.getUserDesc());
        taskVO.setCurrUserCode(reback.getIssuerCode());
        taskVO.setCurrUserName(reback.getIssuerName());
//                taskVO.setCompCode(user.getCompCode());
//                taskVO.setCompName(user.getCompName());
        taskVO.setPageUrl("/jlta/taskcopy/taskA02");
        taskVO = (FltdTask) BeanUtils.initBean(taskVO);
        taskVO.setTodoGuid(TodoGuid);
        taskVO.setTodoType("8");
        taskVO.setStatus("open");
        taskVO.setStatusName("进行中");
        taskVO.setRemark("提交");
        taskVO.setFactStartDate(new Date());
        fltdTaskService.insert(taskVO);
        // 发送通知
        XtzyUser userMsg = new XtzyUser();
        userMsg.setUserCode(fltdTask.getCurrUserCode());
        userMsg.setUserDesc(fltdTask.getCurrUserName());
        userMsg.setExt1("");
        userMsg.setExt2("");
        userMsg.setExt3("close");
        socketServer.sendTaskMsgToAll(userMsg);
        userMsg = new XtzyUser();
        userMsg.setUserCode(getUser().getUserCode());
        userMsg.setUserDesc(getUser().getUserDesc());
        userMsg.setExt1("");
        userMsg.setExt2("");
        userMsg.setExt3("open");
        socketServer.sendTaskMsgToAll(userMsg);
        return success();
    }

    @PostMapping("doApportion")
    @ApiOperation("分配任务到人")
    @Transactional
    public AjaxResult doApportion(@RequestBody MutiTeamVO mutiTeamVO) {
        //取必要数据
        XtzyUser sysUser = getUser();
        String teamId = mutiTeamVO.getTeamId();
        JltaTaskVO task = mutiTeamVO.getJltaTaskVO();
        List<JltaTeamUserVO> teamUserList = mutiTeamVO.getTeamUserVOList();
        String role = getRole(sysUser, teamId);
        if ("0".equals(role)) {
            return error("当前用户没有操作权限！");
        }
        //1、先删除当前任务下的所有反馈任务
        rebackService.deleteByTaskGuid(task.getId());
        if (CollectionUtils.isNotEmpty(teamUserList)) {
            StringBuffer assignNames = new StringBuffer();
            StringBuffer assignCodes = new StringBuffer();
            teamUserList.forEach(n -> {
                //2、有几个人就分配多少条反馈任务，后新增
                JltaReback jltaReback = new JltaReback();
                jltaReback.setTeamId(teamId);
                jltaReback.setTeamName(task.getTeamName());
                jltaReback.setRemark(task.getRemark());
                jltaReback.setTaskId(task.getId());
                jltaReback.setTaskName(task.getTaskName());
                jltaReback.setUserCode(n.getUserCode());
                jltaReback.setUserDesc(n.getUserName());
                jltaReback.setStatus("01");
                jltaReback.setStatusName("草稿");
                jltaReback.setProirity(task.getPriority());
                jltaReback.setIssuerCode(sysUser.getUserCode());
                jltaReback.setIssuerName(sysUser.getUserDesc());
                jltaReback.setPlanDate(task.getPlanDate());//计划完成时间
                jltaReback.setExt2(UUID.randomUUID().toString());//待办TodoGuid
                jltaReback = (JltaReback) BeanUtils.initBean(jltaReback);
                rebackService.insert(jltaReback);
                // //拼接审批人名字，放入任务表字段
                assignNames.append(n.getUserName());
                assignNames.append(",");
                assignCodes.append(n.getUserCode());
            });
            assignCodes.append(task.getId());
            //更新任务主表
            String substring = assignNames.substring(0, assignNames.length() - 1);
            JltaTask taskQ = new JltaTask();
            taskQ.setId(task.getId());
            taskQ.setStatus("3");
            taskQ.setStatusName("已分配");
            taskQ.setAssign(substring);
            jltaTaskService.update(taskQ);
        }
        return success();
    }

    @PostMapping("doReturnTask")
    @ApiOperation("退回任务==重新产生待办")
    @Transactional
    public AjaxResult doReturnTask(@RequestBody JltaReback reback) {
        Date now = new Date();
        FltdTask fltdTask = fltdTaskService.selectTaskByTodoGuid(reback.getExt2());
        fltdTask.setStatus("close");
        fltdTask.setStatusName("完成");
        fltdTask.setAuditCode(getUser().getUserCode());
        fltdTask.setAuditName(getUser().getUserDesc());
        fltdTask.setFactEndDate(now);
        fltdTask.setUpdateBy(getUserName());
        fltdTask.setUpdateTime(now);
        int i = fltdTaskService.updateTaskStatus(fltdTask);
        //重新生成待办
        //2,更新反馈表属性,状态改为 03:已提交
        String TodoGuid = UUID.randomUUID().toString();
        reback.setExt2(TodoGuid);
        reback.setStatus("02");
        reback.setStatusName("已下发");
        rebackService.update(reback);
        XtzyUser user = getUser();
        String acctYear = DateUtils.format(new Date(), "yyyy");
        String quarterCurrent = DateUtils.getQuarter(new Date());
        FltdTask taskVO = new FltdTask();
        taskVO.setFlowNo("renwuzhongxin");
        taskVO.setFlowName("任务中心");
        taskVO.setAcctYear(acctYear);
        taskVO.setQuarterCode(quarterCurrent);
        taskVO.setQuarterName(DateUtils.getQuarterName(taskVO.getQuarterCode()));
        taskVO.setBizGuid(reback.getId());
        taskVO.setGroupFlag("N");
        String bizDesc = reback.getTaskName() + "-" + reback.getTeamName();
        taskVO.setBizDesc(bizDesc);
        taskVO.setBeforeUserCode(reback.getIssuerCode());
        taskVO.setBeforeUserName(reback.getIssuerName());
        taskVO.setCurrUserCode(reback.getUserCode());
        taskVO.setCurrUserName(reback.getUserDesc());
//                taskVO.setCompCode(user.getCompCode());
//                taskVO.setCompName(user.getCompName());
        taskVO.setPageUrl("/jlta/taskcopy/taskA01");
        taskVO = (FltdTask) BeanUtils.initBean(taskVO);
        taskVO.setTodoGuid(TodoGuid);
        taskVO.setTodoType("8");
        taskVO.setStatus("open");
        taskVO.setStatusName("进行中");
        taskVO.setRemark("提交");
        taskVO.setFactStartDate(new Date());
        fltdTaskService.insert(taskVO);
        // 发送通知
        XtzyUser userMsg = new XtzyUser();
        userMsg.setUserCode(fltdTask.getCurrUserCode());
        userMsg.setUserDesc(fltdTask.getCurrUserName());
        userMsg.setExt1("");
        userMsg.setExt2("");
        userMsg.setExt3("close");
        socketServer.sendTaskMsgToAll(userMsg);
        userMsg = new XtzyUser();
        userMsg.setUserCode(reback.getUserCode());
        userMsg.setUserDesc(reback.getUserDesc());
        userMsg.setExt1("");
        userMsg.setExt2("");
        userMsg.setExt3("open");
        socketServer.sendTaskMsgToAll(userMsg);
        return success();
    }

    @PostMapping("doFinishTask")
    @ApiOperation("完成任务")
    public AjaxResult doFinishTask(@RequestBody JltaReback reback) {
        Date now = new Date();
        FltdTask fltdTask = fltdTaskService.selectTaskByTodoGuid(reback.getExt2());
        fltdTask.setStatus("close");
        fltdTask.setStatusName("完成");
        fltdTask.setAuditCode(getUser().getUserCode());
        fltdTask.setAuditName(getUser().getUserDesc());
        fltdTask.setFactEndDate(now);
        fltdTask.setUpdateBy(getUserName());
        fltdTask.setUpdateTime(now);
        int i = fltdTaskService.updateTaskStatus(fltdTask);
        // 发送通知
        XtzyUser userMsg = new XtzyUser();
        userMsg.setUserCode(getUser().getUserCode());
        userMsg.setUserDesc(getUser().getUserCode());
        userMsg.setExt1("");
        userMsg.setExt2("");
        userMsg.setExt3("close");
        socketServer.sendTaskMsgToAll(userMsg);
        reback.setStatus("04");
        reback.setStatusName("已完成");
        rebackService.update(reback);
        JltaReback rebackQ = new JltaReback();
        rebackQ.setTaskId(reback.getTaskId());
        List<JltaReback> select = rebackService.select(rebackQ);
        boolean flag = true;//是否全部完成，若分配任务全部完成，将任务表状态改为完成
        for (JltaReback reback1 : select) {
            if (!"04".equals(reback1.getStatus())) {
                flag = false;
            }
        }
        if (flag){
            JltaTask jltaTask = taskMapper.selectByPrimaryKey(reback.getTaskId());
            jltaTask.setStatus("5");
            jltaTask.setStatusName("完成");
            taskMapper.updateByPrimaryKeySelective(jltaTask);
        }
        return success();
    }

    @GetMapping("getRebackById")
    @ApiOperation("根据Id查询反馈表信息")
    public AjaxResult getReback(JltaReback reback) {
        return success(rebackService.getReback(reback));
    }

    @GetMapping("selectRebacklist")
    @ApiOperation("根据任务表查询反馈表信息")
    public AjaxResult selectRebacklist(JltaReback reback) {
        startPage();
        return getResultPage(rebackService.selectRebacklist(reback));
    }

    @PostMapping(value = "saveReback")
    @ApiOperation("保存查询反馈表信息")
    public AjaxResult saveReback(HttpServletRequest request) throws IOException {
        //转换request
        ShiroHttpServletRequest shiroRequest = (ShiroHttpServletRequest) request;
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        MultipartHttpServletRequest multipartRequest = commonsMultipartResolver.resolveMultipart((HttpServletRequest) shiroRequest.getRequest());
        //获取页面传参
        String businessCode = multipartRequest.getParameter("businessCode");
        String rebackId = multipartRequest.getParameter("rebackId");//反馈表Id
        String reback = multipartRequest.getParameter("reback");//反馈表Id


        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        if (fileMap.size() != 0 && fileMap != null) {
            xtdcAttachService.deleteFilesBySourceAndModel(rebackId, "T_JLTA_TASK");
            for (String key : fileMap.keySet()) {
                //获取附件

                MultipartFile multipartFile = fileMap.get(key);
                InputStream inputStream = multipartFile.getInputStream();
                String filename = multipartFile.getOriginalFilename();
                long fileSize = multipartFile.getSize();

                FileManager.Config config = fileManager.getConfig();
                config.setInputStream(inputStream);
                config.setBusinessCode(businessCode);
                config.setFilename(filename);

                //生成目录
                String dir = fileManager.generateDir(config);
                String filepath = dir + "/" + filename;
                //保存文件
                multipartFile.transferTo(new File(filepath));
                String fileType = "file";
                int indx = filename.lastIndexOf(".");
                if (indx > 0 && indx < filename.length() - 1) {
                    fileType = filename.substring(indx + 1).toLowerCase();
                }
                //存入数据库
                XtdcAttach attach = (XtdcAttach) BeanUtils.initBean(new XtdcAttach());
                attach.setFileName(filename);
                attach.setFilePath(filepath);
                attach.setFileSize(fileSize);
                attach.setFileType(fileType);
                attach.setFolderId("1");
                attach.setSourceGuid(rebackId);
                attach.setSourceModel("T_JLTA_TASK");
                xtdcAttachService.insert(attach);
            }
        }
        JltaReback rebackQ = new JltaReback();
        rebackQ.setId(rebackId);
        rebackQ.setReback(reback);
        rebackService.update(rebackQ);


        return success("保存成功");
    }
}

